package neatlogic.module.change.api.sop;

import neatlogic.framework.auth.core.AuthAction;
import neatlogic.framework.common.constvalue.ApiParamType;
import neatlogic.framework.restful.constvalue.OperationTypeEnum;
import neatlogic.framework.restful.annotation.Description;
import neatlogic.framework.restful.annotation.Input;
import neatlogic.framework.restful.annotation.OperationType;
import neatlogic.framework.restful.annotation.Param;
import neatlogic.framework.restful.core.privateapi.PrivateApiComponentBase;
import neatlogic.module.change.auth.label.CHANGE_MODIFY;
import neatlogic.module.change.dao.mapper.ChangeTemplateMapper;
import neatlogic.framework.change.dto.ChangeSopVo;
import neatlogic.framework.change.exception.ChangeSopIsReferencedException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
@OperationType(type = OperationTypeEnum.DELETE)
@AuthAction(action = CHANGE_MODIFY.class)
public class ChangeSopDeleteApi extends PrivateApiComponentBase {
    
    @Resource
    private ChangeTemplateMapper changeTemplateMapper;

    @Override
    public String getToken() {
        return "change/sop/delete";
    }

    @Override
    public String getName() {
        return "删除变更sop模板";
    }

    @Override
    public String getConfig() {
        return null;
    }
    
    @Input({
        @Param(name = "changeSopId", type = ApiParamType.LONG, isRequired = true, desc = "变更sop模板id")
    })
    @Description(desc = "删除变更sop模板")
    @Override
    public Object myDoService(JSONObject jsonObj) throws Exception {
        Long changeSopId = jsonObj.getLong("changeSopId");
        ChangeSopVo changeSopVo = changeTemplateMapper.getChangeSopById(changeSopId);
        if(changeSopVo != null) {
            /** 变更sop模板被引用后，不能删除 **/
            List<Long> changeTemplateIdList = changeTemplateMapper.getChangeTemplateIdListByChangeSopId(changeSopId);
            if(CollectionUtils.isNotEmpty(changeTemplateIdList)) {
                throw new ChangeSopIsReferencedException(changeSopVo.getName());
            }
            changeTemplateMapper.deleteChangeSopById(changeSopId);
            changeTemplateMapper.deleteChangeSopStepByChangeSopId(changeSopId);
            changeTemplateMapper.deleteChangeSopStepUserByChangeSopId(changeSopId);
            changeTemplateMapper.deleteChangeSopStepTeamByChangeSopId(changeSopId);
            changeTemplateMapper.deleteChangeSopStepContentByChangeSopId(changeSopId);
            changeTemplateMapper.deleteChangeSopStepFileByChangeSopId(changeSopId);
        }        
        return null;
    }

}
